"""
Claude integration module for GSI Wiki Generator
"""

import subprocess
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Dict, List
import logging

logger = logging.getLogger(__name__)


class ClaudeIntegration:
    """Handles Claude AI integration for generating technical answers"""
    
    def __init__(self, config, claude_answers_dir: Path, search_context_file: Path):
        self.config = config
        self.claude_answers_dir = claude_answers_dir
        self.search_context_file = search_context_file
    
    def call_claude_with_background(self, question: str) -> str:
        """Call Claude with background information from search results"""
        
        prompt = f"""
基于提供的代码库搜索结果，请详细回答以下GSI DRP-4DVar实施问题：

**问题**: {question}

**要求**:
1. 基于背景文件中的代码库搜索结果提供具体技术解答
2. 包含实际的代码示例和文件路径引用
3. 提供具体的实施步骤和配置参数
4. 指出可能的风险点和解决方案
5. 使用中文回答，技术术语准确

请参考背景文件中的搜索结果来回答这个问题。
"""
        
        logger.info(f"Calling Claude for question: {question[:50]}...")
        
        try:
            # Use Claude with the background file
            result = subprocess.run([
                'claude', '-p', prompt, str(self.search_context_file)
            ], capture_output=True, text=True, encoding='utf-8', timeout=self.config.claude_timeout)
            
            if result.returncode == 0:
                answer = result.stdout.strip()
                logger.info(f"Claude answered successfully ({len(answer)} characters)")
                
                # Save individual Claude answer to file
                self._save_claude_answer(question, answer)
                
                return answer
            else:
                error_msg = f"Claude call failed: {result.stderr}"
                logger.error(error_msg)
                return f"[Claude调用失败: {error_msg}]"
                
        except subprocess.TimeoutExpired:
            logger.error("Claude call timed out")
            return "[Claude调用超时]"
        except Exception as e:
            logger.error(f"Error calling Claude: {str(e)}")
            return f"[Claude调用错误: {str(e)}]"
    
    def _save_claude_answer(self, question: str, answer: str) -> None:
        """Save individual Claude answer to file"""
        # Create safe filename from question
        safe_filename = "".join(c for c in question if c.isalnum() or c in (' ', '-', '_')).rstrip()
        safe_filename = safe_filename.replace(' ', '_')[:50]  # Limit length
        
        answer_file = self.claude_answers_dir / f"{safe_filename}.md"
        
        with open(answer_file, 'w', encoding='utf-8') as f:
            f.write(f"# {question}\n\n")
            f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            f.write(answer)
        
        logger.info(f"Claude answer saved to: {answer_file}")
    
    def generate_answers_for_questions(self, questions: List[str], progress_cache: Dict) -> Dict[str, str]:
        """Generate Claude answers for all questions, with caching support"""
        enhanced_answers = {}
        
        for question in questions:
            # Check if this question was already answered
            if question in progress_cache.get("completed_questions", []):
                logger.info(f"Skipping already answered question: {question[:50]}...")
                # Load cached answer if available
                if question in progress_cache.get("claude_answers", {}):
                    enhanced_answers[question] = progress_cache["claude_answers"][question]
                continue
                
            logger.info(f"Processing new question: {question[:50]}...")
            answer = self.call_claude_with_background(question)
            enhanced_answers[question] = answer
            
            # Update cache would be handled by the calling function
            
        return enhanced_answers